package com.luo.backend.controller;

import com.luo.backend.common.ApiResponse;
import com.luo.backend.dto.AIChatRequest;
import com.luo.backend.dto.AIChatResponse;
import com.luo.backend.service.AIService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

/**
 * AI聊天控制器
 */
@RestController
@RequestMapping("/api/v1/ai")
public class AIController {
    
    private static final Logger logger = LoggerFactory.getLogger(AIController.class);
    
    @Autowired
    private AIService aiService;
    
    /**
     * AI聊天接口
     * 
     * POST /api/v1/ai/chat
     * 需要认证：是（JWT Token）
     */
    @PostMapping("/chat")
    public ApiResponse<AIChatResponse> chat(@RequestBody AIChatRequest request) {
        logger.info("收到AI聊天请求：{}", request.getMessage());
        
        // 1. 验证消息内容
        if (request.getMessage() == null || request.getMessage().trim().isEmpty()) {
            return ApiResponse.error(400, "消息内容不能为空");
        }
        
        // 限制消息长度（防止恶意攻击）
        if (request.getMessage().length() > 500) {
            return ApiResponse.error(400, "消息内容过长，请控制在500字以内");
        }
        
        try {
            // 2. 获取当前用户ID
            Long userId = (Long) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            
            // 3. 调用AI服务
            String reply = aiService.chat(request.getMessage(), userId);
            
            // 4. 构建响应
            AIChatResponse response = new AIChatResponse();
            response.setReply(reply);
            
            // 生成会话ID（如果前端没传）
            if (request.getConversationId() != null && !request.getConversationId().isEmpty()) {
                response.setConversationId(request.getConversationId());
            } else {
                response.setConversationId("conv_" + System.currentTimeMillis() + "_" + userId);
            }
            
            // 可选：添加建议（后续可扩展）
            // response.setSuggestions(Arrays.asList("查看热门商品", "了解拼单活动"));
            
            logger.info("AI聊天成功，会话ID：{}", response.getConversationId());
            return ApiResponse.success(response);
            
        } catch (Exception e) {
            logger.error("AI聊天失败", e);
            return ApiResponse.serverError("AI服务暂时不可用，请稍后重试");
        }
    }
    
    /**
     * 健康检查接口（可选）
     */
    @GetMapping("/health")
    public ApiResponse<String> health() {
        return ApiResponse.success("AI服务运行正常");
    }
}



